<?php

namespace addons\qingdongams\model;

use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *线索
 */
class Leads Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdongams_leads';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	public function getCreatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	public function getUpdatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	//创建人
	public function createStaff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name');
	}


	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
	}
    //转派人
    public function tranferStaff() {
        return $this->hasOne(Staff::class, 'id', 'tranfer_stff_id')->field('id,name,img');
    }

    //获取线索相关信息
    public function leadsOther() {
        return $this->belongsTo(LeadsOther::class,'id','id');
    }

	//创建线索
	public static function createLeads($params=array(),$pool=null) {
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr( $name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if(empty($params[$name])){
                    $params[$name]=NULL;
                }
            }
		}
		$staff                     = Staff::info();
        if(!empty($staff)){
            $params['create_staff_id'] = $staff->id;
            $params['owner_staff_id']  = $staff->id;
        }
        //后台添加线索
        if(isset($params['staff_id']) && $params['staff_id']){
            $params['create_staff_id'] = $params['staff_id'];
            $params['owner_staff_id']  = $params['staff_id'];
        }
        //线索池
        if($pool){
            $params['owner_staff_id']  = '';
        }
		$Model                     = new self;
        $result = $Model->allowField(true)->save($params);
		$lastId = $Model->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}
		//其他信息
		$otherModel = new LeadsOther();
		if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        $remind = Remind::where(['type'=>'add_lead'])->find();
        if($remind && $remind['staff_ids']){
            $remind_staff = explode(',',$remind['staff_ids']);
            foreach($remind_staff as $kr=>$vr){
                Message::addMessage(Message::LEADADD_TYPE,$lastId,$vr,$staff->id);
            }
        }

		return $lastId;
	}


	/**
	 *修改线索
	 */
	public static function updateLeads($params) {
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}
		//其他信息
		$otherModel = new LeadsOther();
		if ($otherModel->save([ 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)],['id' =>  $params['id']]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}

		return true;
	}
    //客户
    public function customer() {
        return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,follow');
    }

    //导入线索
    public static function importleads($data) {
        $addleads = [];
        $addOther     = [];
        $addLog=[];
        foreach ($data as $params) {
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }else{
                    if(empty($params[$name])){
                        $params[$name]=NULL;
                    }
                }
            }
            $other['id']           = $params['id'];
            $params['next_time']   = date('Y-m-d H:i:s');
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addLog[] = [
                'content'        => '导入线索',
                'operation_type' => 4,
                'operation_id'   => isset($params['owner_staff_id'])?$params['owner_staff_id']:$params['create_staff_id'],
                'relation_type'  => OperationLog::LEADS_TYPE,
                'relation_id'    => $params['id'],
                'createtime'     => time()
            ];
            $addleads[]        = $params;
        }

        $leads = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $leads->allowField(true)->insertAll($addleads);

        $otherModel = new LeadsOther();
        if($other){
            $otherModel->allowField(true)->insertAll($addOther);
        }

        $logModel = new OperationLog();
        $logModel->allowField(true)->insertAll($addLog);

        return true;
    }

    /**
     * 转移线索
     */
    public static function transfer($id, $staff_id) {

        Db::startTrans();
        try {
            $staff                     = Staff::info();
            //批量转移
            if(is_array($id)){
                foreach($id as $k=>$v){
                    if (self::where(['id' => $v])->update([
                            'owner_staff_id' => $staff_id,
                            'tranfer_stff_id' => $staff->id,
                            'receive_time'=>time(),
                            'updatetime'     => time()
                        ]) == false) {
                        throw new Exception('修改失败');
                    }
                    $staff = Staff::get($staff_id);
                    Message::addMessage(Message::LEADSPOOL_ACHIEVE,$v,$staff_id,$staff->id);
                    OperationLog::createLog(OperationLog::LEADS_TYPE, $v,
                        '将线索转移给：' . $staff['name']);
                }
            }else{
                if (self::where(['id' => $id])->update([
                        'owner_staff_id' => $staff_id,
                        'tranfer_stff_id' => $staff->id,
                        'receive_time'=>time(),
                        'updatetime'     => time()
                    ]) == false) {
                    throw new Exception('修改失败');
                }
                $staff = Staff::get($staff_id);
                Message::addMessage(Message::LEADSPOOL_ACHIEVE,$id,$staff_id,$staff->id);
                OperationLog::createLog(OperationLog::LEADS_TYPE, $id,
                    '将线索转移给：' . $staff['name']);
            }


            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        return true;
    }
    /**
     *移入公海
     */
    public static function movePool($id) {


        if (self::where(['id' => $id])->update(['owner_staff_id' => 0,'updatetime'=>time()]) == false) {
            throw new Exception('修改失败');
        }
        $staff                     = Staff::info();
        $remind = Remind::where(['type'=>'leads_tranfer'])->find();
        if($remind && $remind['staff_ids']){
            $remind_staff = explode(',',$remind['staff_ids']);
            foreach($remind_staff as $kr=>$vr){
                Message::addMessage(Message::LEADS_MOVE,$id,$vr,$staff->id);
            }
        }
        OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将线索放入线索池');

        return true;
    }
}
